package com.solve.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.solve.dao.ResourceClassificationMiddleMapper;
import com.solve.dao.ResourceDownloadUserMiddleMapper;
import com.solve.dao.ResourceInfoCommentMapper;
import com.solve.dao.ResourceInfoUserMapper;
import com.solve.entity.*;
import com.solve.remote.UserRemoteService;
import com.solve.shiro.JWTToken;
import org.apache.shiro.SecurityUtils;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

@Service
public class ResourceInfoUseServiceImpl {
    @Resource
    private ResourceInfoUserMapper resourceInfoUserMapper ;

    @Resource
    private ResourceClassificationMiddleMapper resourceClassificationMiddleMapper;

    @Resource
    private ResourceDownloadUserMiddleMapper resourceDownloadUserMiddleMapper;

    @Resource
    private UserRemoteService userRemoteService;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private ResourceInfoCommentMapper resourceInfoCommentMapper;

    public String  saveResourceInfoReturnId(ResourceInfoUser resourceInfoUser){

        if (StringUtils.isEmpty(resourceInfoUser.getUuid())){
            JWTToken jwtToken = (JWTToken) SecurityUtils.getSubject().getPrincipal();
            resourceInfoUser.setUuid(UUID.randomUUID().toString());
            resourceInfoUser.setUserId(jwtToken.getUserId());
            resourceInfoUserMapper.insert(resourceInfoUser);
            batchInsertResourceInfoMIddle(resourceInfoUser);

        }else{
            ResourceInfoUserExample resourceInfoUserExample = new ResourceInfoUserExample();
            resourceInfoUserExample.createCriteria().andUuidEqualTo(resourceInfoUser.getUuid());
            ResourceClassificationMiddleExample resourceClassificationMiddleExample = new ResourceClassificationMiddleExample();
            resourceClassificationMiddleExample.createCriteria().andResourceInfoIdEqualTo(resourceInfoUser.getUuid());
            resourceClassificationMiddleMapper.deleteByExample(resourceClassificationMiddleExample);
            resourceInfoUserMapper.updateByExampleSelective(resourceInfoUser,resourceInfoUserExample);
            batchInsertResourceInfoMIddle(resourceInfoUser);
        }
        return resourceInfoUser.getUuid();
    }

    public void batchInsertResourceInfoMIddle(ResourceInfoUser resourceInfoUser){

        for (String uuid : resourceInfoUser.getResrourceClassificationList()){
            ResourceClassificationMiddle resourceClassificationMiddle = new ResourceClassificationMiddle();
            resourceClassificationMiddle.setUuid(UUID.randomUUID().toString());
            resourceClassificationMiddle.setResourceClassificationId(uuid);
            resourceClassificationMiddle.setResourceInfoId(resourceInfoUser.getUuid());
            resourceClassificationMiddleMapper.insert(resourceClassificationMiddle);
        }

    }

    public PageInfo getResourceInfoUserByPageInfo(ResourceInfoUser resourceInfoUser){
        PageHelper.startPage(resourceInfoUser.getPageNum(),resourceInfoUser.getPageSize());
        ResourceInfoUserExample resourceInfoUserExample = new ResourceInfoUserExample();
        ResourceInfoUserExample.Criteria criteria = resourceInfoUserExample.createCriteria();

        if (resourceInfoUser.getResrourceClassificationList().size() > 0){
            criteria.andClassificationIn(resourceInfoUser.getResrourceClassificationList());
        }

        if (!StringUtils.isEmpty(resourceInfoUser.getContent())){
            criteria.andTitleLike(resourceInfoUser.getContent());
        }

        List<ResourceInfoUser> resourceInfoUserList = resourceInfoUserMapper.selectByExampleWithBLOBs(resourceInfoUserExample);
        PageInfo<ResourceInfoUser> pageInfo = new PageInfo<ResourceInfoUser>(resourceInfoUserList);
        return pageInfo;
    }

    public ResourceInfoUserExtend getResourceInfoUserInfo(ResourceInfoUser resourceInfoUser){
        ResourceInfoUser resourceInfoUserDb = resourceInfoUserMapper.selectByPrimaryKey(resourceInfoUser.getUuid());

        //检查当前资源是否已经被下载了
        JWTToken jwtToken = (JWTToken) SecurityUtils.getSubject().getPrincipal();
        ResourceDownloadUserMiddleExample resourceDownloadUserMiddleExample = new ResourceDownloadUserMiddleExample();
        resourceDownloadUserMiddleExample.createCriteria().andDownloadUserIdEqualTo(jwtToken.getUserId())
                                                          .andResourceIdEqualTo(resourceInfoUser.getUuid());

        int recordNum =  resourceDownloadUserMiddleMapper.countByExample(resourceDownloadUserMiddleExample);
        ResourceInfoUserExtend resourceInfoUserExtend = new ResourceInfoUserExtend();
        if (recordNum != 0){
            resourceInfoUserExtend.setExchange(true);
        }else{
            resourceInfoUserExtend.setExchange(false);
        }

        //检查当前用户是否可以再次评论
        ResourceInfoCommentExample resourceInfoCommentExample = new ResourceInfoCommentExample();
        resourceInfoCommentExample.createCriteria().andResourceIdEqualTo(resourceInfoUser.getUuid())
                                                   .andCreatoridEqualTo(jwtToken.getUserId());
        int countNum = resourceInfoCommentMapper.countByExample(resourceInfoCommentExample);
        if (countNum != 0){
            resourceInfoUserExtend.setCanComment(false);//评论过的,不能再次评论
        }else{
            resourceInfoUserExtend.setCanComment(true);//评论过的,不能再次评论
        }


        resourceInfoUserExtend.setResourceInfoUser(resourceInfoUserDb);
        return resourceInfoUserExtend;
    }

    public void exchangeResource(ResourceInfoUser resourceInfoUser) throws Exception{
        //首选要判断当前用户积分是否足够用

        JWTToken jwtToken = (JWTToken) SecurityUtils.getSubject().getPrincipal();
        User user = userRemoteService.getUserAllInfo(jwtToken.getUserId());

        resourceInfoUser = resourceInfoUserMapper.selectByPrimaryKey(resourceInfoUser.getUuid());

        if (resourceInfoUser.getCostGrade() > user.getIntegral()){
            throw new Exception("当前积分不足");
        }


        ResourceInfoUserExtend resourceInfoUserExtend = new ResourceInfoUserExtend();
        resourceInfoUserExtend.setResourceInfoUser(resourceInfoUser);
        resourceInfoUserExtend.setCurrentUser(user);

        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(UUID.randomUUID().toString());
        String direct = "direct";

        //请求消息到指定路由中
        rabbitTemplate.convertAndSend(direct,"user1",JSONObject.toJSONString(resourceInfoUserExtend),correlationData);

        //更新当前资源与用户状态表
        ResourceDownloadUserMiddle resourceDownloadUserMiddle = new ResourceDownloadUserMiddle();
        resourceDownloadUserMiddle.setResourceId(resourceInfoUser.getUuid());
        resourceDownloadUserMiddle.setUuid(UUID.randomUUID().toString());
        resourceDownloadUserMiddle.setDownloadUserId(user.getUuid());
        resourceDownloadUserMiddleMapper.insert(resourceDownloadUserMiddle);

        //下载量增加1
        resourceInfoUserMapper.addResourceInfoUDownloadNum(resourceInfoUser);
    }

    public ResourceInfoUser getResourceInfoUserDetailInfo(ResourceInfoUser resourceInfoUser){
        resourceInfoUser = resourceInfoUserMapper.selectResourceInfoUserDetailByPrimaryKey(resourceInfoUser.getUuid());
        return resourceInfoUser;
    }
}
